/* 
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */




//测量距离函数



function getLengthCalculator() {
    return new OpenLayers.Control.Measure(OpenLayers.Handler.Path, h_options);
}

function stylemap() {
    var sketchSymbolizers = {
        "Point" : {
            pointRadius : 4,
            graphicName : "square",
            fillColor : "white",
            fillOpacity : 1,
            strokeWidth : 1,
            strokeOpacity : 1,
            strokeColor : "#FF0000"
        },
        "Line" : {
            strokeWidth : 3,
            strokeOpacity : 1,
            strokeColor : "#FFFF00"
        },
        "Polygon" : {
            strokeWidth : 2,
            strokeOpacity : 1,
            strokeColor : "#FFFF00",
            fillColor : "white",
            fillOpacity : 0.3
        }
    };

    var style = new OpenLayers.Style();
    style.addRules([new OpenLayers.Rule({
        symbolizer : sketchSymbolizers
    })]);
    var styleMap = new OpenLayers.StyleMap({
        "default" : style
    });

    return styleMap;
}

var prevPopup = null;
var showFans = false, showMode = 0;
function clearMeasure() {
    if (prevPopup) {
        prevPopup.close();
    }
    prevPopup = null
}

var h_options = {
    handlerOptions : {
        style : "default",
        layerOptions : {
            styleMap : stylemap()
        },
        persist : true
    },
    eventListeners : {
        'measure' : renderMoveCell,
        'measurepartial' : clearMeasure,
        'deactivate' : clearMeasure
    }
};

function renderMoveCell(event) {
    function calcVincenty(geometry) {
        var dist = 0;
        for (var i = 1; i < geometry.components.length; i++) {
            var first = geometry.components[i - 1];
            var second = geometry.components[i];
            dist += OpenLayers.Util.distVincenty({
                lon : first.x,
                lat : first.y
            }, {
                lon : second.x,
                lat : second.y
            });
        }
        return dist;
    }

    var geometry = event.geometry;
    var units = event.units;
    var order = event.order;
    var measure = event.measure;
    var out = "";

    // show cellGrid float Window
    if (showFans) {
        pars = "(";
        points = geometry.components[0];

        for (var i = 0; i < points.components.length - 1; i++) {
            var pt = points.components[i];
            pars = pars + pt.x + ' ' + pt.y + ',';
        }

        var pt = points.components[0];
        pars = pars + pt.x + ' ' + pt.y + ')';
        var cell_bounds = pars;
        cellGrid.show();
        if (cellGrid.collapsed)
            cellGrid.expand(true);
        store_bounds.load({
            params : {
                bounds : pars
            }
        });
    } else {

        if (order == 1) {
            out += measure.toFixed(3) + " " + units;
            createPopup(out);
            return;
        } else {
            out += "面积:" + measure.toFixed(3) + " " + units + "<sup>2</sup>";
        }
        createPopup(out);

        var bounds = "(";
        var points = geometry.components[0];

        for (var i = 0; i < points.components.length - 1; i++) {
            var pt = points.components[i];
            bounds = bounds + pt.x + ' ' + pt.y + ',';
        }

        var pt = points.components[0];
        bounds = bounds + pt.x + ' ' + pt.y + ')';

        pars = {
            bounds : bounds,
            cur_time : cur_time
        };
        new Ajax.Request("/map/geterl9", {
            method : "POST",
            parameters : pars,
            onComplete : function(request) {

                places = eval("(" + request.responseText + ")");

                if (request.responseText.length > 10) {
                    place = places[0];
                    erl = parseFloat(place["user"]["sum"]);
                    if (isNaN(erl))
                        erl = 0;
                    var hw_str = erl.toFixed(5);
                    out += '<br>' + '900话务量: ' + hw_str;
                    createPopup(out);
                }
            }
        });

        new Ajax.Request("/map/geterl18", {
            method : "POST",
            parameters : pars,
            onComplete : function(request) {

                places = eval("(" + request.responseText + ")");

                if (request.responseText.length > 10) {
                    place = places[0];
                    erl = parseFloat(place["user"]["sum"]);
                    if (isNaN(erl))
                        erl = 0;
                    hw_str = erl.toFixed(5);
                    out += '<br>' + '1800话务量: ' + hw_str;
                    createPopup(out);
                }
            }
        });
    }
}

function clearMeasure() {
    if (prevPopup) {
        prevPopup.close();
    }
    prevPopup = null
}

function createPopup(value) {
    clearMeasure();
    var html = value;
    var popup = new Ext.Window({
        title : '测量结果',
        html : html,
        width : 200,
        bodyStyle : 'background-color:#FFFFD0;'
    });
    prevPopup = popup;
    popup.show();
}

//测量距离结束

//天线搜索


var store_cell = new Ext.data.JsonStore({
    url:'/map/getcellstore',
    root:'rows',
    baseParams:{
        limit: 15,
        query : ""
    },
    totalProperty:'results',
    fields : ['cell_id',
    'grid_id',
    'cellname',
    'bcchno',
    'bsic',
    'tch',
    'bspwrb',
    'antennagain',
    'height',
    'direction',
    'vange',
    'celltype',
    'addr',
    'the_geom',
    'cell_emluator_model',
    'type_code'
    ],
    remoteSort: true
});

var rowExpander = new Ext.grid.RowExpander({
    tpl: new Ext.Template(
        '<div class="x-grid-group-title" style="margin-left:0%"><ol type=1><li style="background-color:#FFFFFF">cell_id:{cell_id}</li><li style="background-color:#F1F6F7">grid_id:{grid_id}</li><li style="background-color:#FFFFFF">cellname:{cellname}</li><li style="background-color:#F1F6F7">bsic:{bsic}</li><li style="background-color:#FFFFFF">bcchno:{bcchno}</li><li style="background-color:#F1F6F7">the_geom:{the_geom}</li><li style="background-color:#FFFFFF">tch:{tch}</li><li style="background-color:#F1F6F7">bspwrb:{bspwrb}</li><li style="background-color:#FFFFFF">antennagain:{antennagain}</li><li style="background-color:#F1F6F7">height:{height}</li><li style="background-color:#FFFFFF">direction:{direction}</li><li style="background-color:#F1F6F7">vange:{vange}</li><li style="background-color:#FFFFFF">celltype:{celltype}</li><li style="background-color:#F1F6F7">addr:{addr}</li><li style="background-color:#FFFFFF">cell_emluator_model:{cell_emluator_model}</li><li style="background-color:#F1F6F7">type_code:{type_code}</li></ol></div>'
        )
});

var cm_cell = new Ext.grid.ColumnModel({
    columns: [
    rowExpander,
    {
        header: "cell_id",
        width: 140,
        dataIndex: 'cell_id'
    },

    {
        header: "cellname",
        width: 160,
        dataIndex: 'cellname'
    },
   

    ],
    defaults : {
        sortable : true
    }
});

var grid_cell = new Ext.grid.GridPanel({
    store : store_cell,
    //layout : 'fit',
    //resizable: true,
    // width: 400,
    height:440,
    //autofill : true,
    //autoScroll : true,

    tbar : ['搜索: ', '', new Ext.ux.form.SearchField({
        id : 'shao',
        store : store_cell,
        xtype: 'twintriggerfield',
        // height : 50,
        width : 250
    })],

    cm : cm_cell,
    plugins: rowExpander,
    

    bbar : new Ext.PagingToolbar({
        store : store_cell,
        pageSize : 15,
        displayInfo : true,
        displayMsg : ' {0} - {1} of {2}',
        emptyMsg : "没有找到！"
    // prependButtons: true
    })
});

grid_cell.on("rowclick", function(grid, rowIndex, e) {
    var row = grid.store.getAt(rowIndex);
    cellname=row.data["cell_id"];
    singlecell.params.VIEWPARAMS='cellname:'+cellname;
    
    panto_id(row.data["cell_id"]);
    singlecell.redraw();
});

var cellwin = new Ext.Window({
    title : 'cell查询定位',
    floating : true,
    shadow : true,
    draggable : true,
    collapsible : true,
    collapsed : true,
    closeAction : 'hide',
    //layout: 'fit',
    //resizable: true,
    width : 420,
    //height: 490,
    autofill : true,
    autoScroll : true,
    plain : true,
    x : 300,
    y : 120,
    items : grid_cell
});

//function showSearch() {
// store_cell.load({params:{}});
//  if(cellwin.show){
//    cellwin.hide()
//}else{
//  cellwin.show()
//}
//cellwin.hide();
//Ext.fly('shao').up('div').setWidth(300,true);
//}

function panto_id(id) {
    pars = "cell_id=" + id;
    new Ajax.Request("/map/get_id", {
        method : "POST",
        parameters : pars,
        onComplete : function(request) {
            var vals = eval("(" + request.responseText + ")");
            var cell = vals[0]["user"];
            var lon = cell["lon"];
            var lat = cell["lat"];
            var lonlat = new OpenLayers.LonLat(lon, lat);
            this.map.panTo(lonlat, {
                animate : true
            });
        }
    });
    return false;
}


//天线搜索结束

function createToolbar(map,lon,lat) {

    var toolbarItems = [];
    var action;

    var createSeparator = function() {
        toolbarItems.push(" ");
        toolbarItems.push("-");
        toolbarItems.push(" ");
    };

    action = new Ext.Action({
        //control: new OpenLayers.Control.ZoomBox(new OpenLayers.Bounds(12559276,2745597,12717000,2576984)),
        //control: new OpenLayers.Control.ZoomToMaxExtent(),
        handler:function(){
            //map.zoomToExtent(new OpenLayers.Bounds(12567051,2750874,12704943,2574458))
            map.setCenter(new OpenLayers.LonLat(lon,lat), 9)
        },
        //map: map,
        iconCls: 'zoomfull',
        toggleGroup: 'map',
        tooltip: '全景'
    });

    toolbarItems.push(action);

    createSeparator();

    action = new GeoExt.Action({
        control: new OpenLayers.Control.ZoomBox(),
        tooltip: '放大',
        map: map,
        iconCls: 'zoomin',
        toggleGroup: 'map'
    });

    toolbarItems.push(action);

    action = new GeoExt.Action({
        control: new OpenLayers.Control.ZoomBox({
            out: true
        }),
        tooltip: '缩小',
        map: map,
        iconCls: 'zoomout',
        toggleGroup: 'map'
    });

    toolbarItems.push(action);

    action = new GeoExt.Action({
        control: new OpenLayers.Control.DragPan({
            isDefault: true
        }),
        tooltip: '拖动地图',
        map: map,
        iconCls: 'pan',
        toggleGroup: 'map'
    });

    toolbarItems.push(action);

    createSeparator();

    action = new GeoExt.Action({
        control: new OpenLayers.Control.DrawFeature(vectorLayer, OpenLayers.Handler.Point),
        tooltip: '标注点',
        map: map,
        iconCls: 'drawpoint',
        toggleGroup: 'map'
    });

    toolbarItems.push(action);


    action = new GeoExt.Action({
        control: getLengthCalculator(),
        tooltip: '测量距离',
        map: map,
        iconCls: 'drawline',
        toggleGroup: 'map'
    });



    toolbarItems.push(action);


    action = new GeoExt.Action({
        control: new OpenLayers.Control.DrawFeature(vectorLayer, OpenLayers.Handler.Polygon),
        tooltip: '标注区域',
        map: map,
        iconCls: 'drawpolygon',
        toggleGroup: 'map'
    });

    toolbarItems.push(action);

    createSeparator();

    ctrl = new OpenLayers.Control.NavigationHistory();
    map.addControl(ctrl);

    action = new GeoExt.Action({
        tooltip: "前一个视图",
        control: ctrl.previous,
        iconCls: 'back',
        disabled: true
    });
    toolbarItems.push(action);

    action = new GeoExt.Action({
        tooltip: "后一个视图",
        control: ctrl.next,
        iconCls: 'next',
        disabled: true
    });
    toolbarItems.push(action);

    createSeparator();

    action = new Ext.Action({
        handler: function() {
            if(cellwin.hidden){
                cellwin.show()
            }else{
                cellwin.hide()
            }
        },
        tooltip: '定位天线',
        map: map,
        iconCls: 'info',
        toggleGroup: 'map'
    });

    toolbarItems.push(action);


    return toolbarItems;
};
